package com.boful.common.net.utils;

import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class NetUtils {

	/***
	 * 获取本机mac地址列表
	 * 
	 * @return key:value 网卡名称:网卡地址
	 */
	public static Map<String, String> getMacAddress() {

		Map<String, String> map = new HashMap<String, String>();
		try {
			Enumeration<NetworkInterface> e = NetworkInterface
					.getNetworkInterfaces();
			while (e.hasMoreElements()) {

				NetworkInterface ni = e.nextElement();
				if (ni.isLoopback() || ni.isPointToPoint() || ni.isVirtual()||(!ni.isUp())) {
					continue;
				}
				byte[] mac = ni.getHardwareAddress();
				if (mac != null) {
					String macString = convertMac(mac);
					String displayName = ni.getDisplayName();
					map.put(displayName, macString);
				}

			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return map;
	}

	private static String convertMac(byte[] mac)

	{

		StringBuffer sb = new StringBuffer();

		for (int i = 0; i < mac.length; i++)

		{

			byte b = mac[i];

			int intValue = 0;

			if (b >= 0) {
				intValue = b;
			} else {
				intValue = 256 + b;
			}
			if (intValue > 9) {
				sb.append(Integer.toHexString(intValue).toUpperCase());
			} else {
				sb.append(paddingZero(intValue));
			}

			if (i != mac.length - 1) {

				sb.append("-");
			}
		}
		return sb.toString();
	}

	private static String paddingZero(int num) {
		if (num > 9) {
			return num + "";
		} else {
			return "0" + num;
		}
	}
	
}
